package ai.fabu.dataplatform.config;


import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.convert.CustomConversions;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.MongoTransactionManager;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.retry.annotation.EnableRetry;

import javax.annotation.Nonnull;

@Configuration
@Slf4j
@EnableRetry
@EnableMongoRepositories(basePackages = "ai.fabu.dataplatform")
public class MongoTransactionConfig extends AbstractMongoConfiguration{
    @Value("${mongodb.database.name}")
    private String databaseName;
    @Value("${mongodb.database.url}")
    private String mongodbURL;


    @Bean
    MongoTransactionManager transactionManager(MongoDbFactory dbFactory) {
        log.info("transactionManager:");
        return new MongoTransactionManager(dbFactory);
    }

    @Override
    @Nonnull
    public String getDatabaseName() {
        return databaseName;
    }

    @Override
    @Nonnull
    public MongoClient mongoClient() {
        return new MongoClient(new MongoClientURI(mongodbURL));
    }

    @Bean(name = "mongoConverter")
    public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context, BeanFactory beanFactory) {
        log.info("mappingMongoConverter: ");
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
        MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
        try {
            mappingConverter.setCustomConversions(beanFactory.getBean(CustomConversions.class));
        } catch (NoSuchBeanDefinitionException ignore) {

        }

        // Don't save _class to mongo
        mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
        return mappingConverter;
    }
}